package com.wufun.overseas.joystick.map;

import android.os.Environment;

import com.wufun.overseas.utils.ConfigFile;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by xiet on 2016/5/3.
 */
public class BlackListManager {
    private final String mapFileDir = Environment.getExternalStorageDirectory().getPath() + "/MG/config";
    private final String TAG        = KeyMapManager.class.getSimpleName();

    private final String     BT_CONFIGURE_FILE_NAME = "blacklist_config.ini";
    private final String[]   BT_CONFIG_SECTIONS     = new String[]{"BT_BLACK_LIST"};
    static        ConfigFile mapIniFile             = null;

    private static BlackListManager instance;

    public BlackListManager() {
        load();
    }

    public static BlackListManager getInstance() {
        if (instance == null) {
            instance = new BlackListManager();
        }

        return instance;
    }

    private File getMapFile() {
        return new File(mapFileDir + "/" + BT_CONFIGURE_FILE_NAME);
    }

    private Map getMap(String sectionTitle) {

        Map<String, String> data = new HashMap<String, String>();
        load();
        ConfigFile               configFile = mapIniFile;
        ConfigFile.ConfigSection section    = configFile.get(sectionTitle);

        Set      set      = section.keySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            String key = (String) iterator.next();
            data.put(key, section.get(key));

        }

        return data;
    }

    /**
     * write [section] KeyMap to config file
     *
     * @param sectionTitle
     * @param data
     * @hide
     */
    private void writeToConfig(String sectionTitle, Map<String, String> data) {
        load();

        Set      set = data.entrySet();
        Iterator i   = set.iterator();
        while (i.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry<String, String>) i.next();
            String                    key   = entry.getKey();
            String                    name  = data.get(key);
            if (mapIniFile != null)
                mapIniFile.put(sectionTitle, name, key);
        }

        save();
    }

    private synchronized void load() {
        File file = getMapFile();
        if (file == null) return;
        String path = file.getAbsolutePath();
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists() && file.isDirectory()) file.delete();
            if (!file.exists()) {
                file.setReadable(true);
                file.setWritable(true);
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mapIniFile == null)
            mapIniFile = new ConfigFile(path);
        if (mapIniFile.reload()) ;
//            prepareData();
    }

    private synchronized void save() {
        try {
            if (mapIniFile != null) {
                mapIniFile.save();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private synchronized static void modifyKeyMap(int gamer, String sectionTitle, String parameter, String value) {
        ConfigFile config = mapIniFile;

        config.put(sectionTitle, parameter, value);
        config.save();
    }

    public boolean isInBlackList(String device) {
        boolean ret = false;
        if (isEmpty(device)) return ret;

        load();
        ConfigFile config = mapIniFile;
        if (config == null) return ret;

        ConfigFile.ConfigSection sectioin = mapIniFile.get(BT_CONFIG_SECTIONS[0]);
        if (sectioin != null) {
            Set<String>      keys     = sectioin.keySet();
            Iterator<String> iterator = keys.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (isEmpty(key)) continue;
                String val = sectioin.get(key);
                if (device.toLowerCase().contains(val.toLowerCase())) {
                    ret = true;
                    break;
                }
            }
        }

        return ret;
    }

    private void clearBlackList() {
        load();

        if (mapIniFile != null) {
            mapIniFile.remove(BT_CONFIG_SECTIONS[0]);
            save();
        }
    }

    public void writeBlackList(List<String> list) {
        if (list == null || list.size() == 0) return;

        load();
        if (mapIniFile == null) return;
        clearBlackList();

        for (int i = 0; i < list.size(); i++) {
            String key = list.get(i);
            mapIniFile.put(BT_CONFIG_SECTIONS[0], key, "");
        }
    }

    public void writeBlackList(Map<String, String> map) {
        if (map == null || map.size() == 0) return;

        load();
        if (mapIniFile == null) return;
        clearBlackList();

        Set<Map.Entry<String, String>>      entrySet = map.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entrySet.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            String                    key   = entry.getKey();
            String                    val   = entry.getValue();
            if (isEmpty(val)) continue;
            mapIniFile.put(BT_CONFIG_SECTIONS[0], key, val);

            save();
        }
    }

    private void prepareData() {
        ConfigFile configFile = mapIniFile;

        for (int j = 0; j < BT_CONFIG_SECTIONS.length; j++) {
            String                   sectionTitle = BT_CONFIG_SECTIONS[j];
            ConfigFile.ConfigSection section      = configFile.get(sectionTitle);

            if (section == null) {
                section = new ConfigFile.ConfigSection(sectionTitle);
                configFile.put(section);

                //TODO: set default value
            }

        }
    }

    private boolean isEmpty(String str) {
        return str == null || str.equals("");
    }

}
